#!/usr/bin/env python
# encoding: utf-8
'''
@author: zhaowenpeng
@contact: winston@peipeiyun.com
@software: garner
@file: encrypt_utiel.py
@time: 2021/2/26 下午2:47
@desc:
'''

import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

class EncryptUtil(object):

    # base64加密
    @staticmethod
    def b64_encrypt(data: (str, bytes)) -> str:
        if isinstance(data, str):
            data = data.encode('utf-8')
        enb64_str = base64.b64encode(data)
        return enb64_str.decode('utf-8')

    # base64解密
    @staticmethod
    def b64_decrypt(data: str) -> str:
        deb64_str = base64.b64decode(data)
        return deb64_str.decode('utf-8')

    # base64对url加密
    @staticmethod
    def url_b64_encrypt(data: str) -> str:
        enb64_str = base64.urlsafe_b64encode(data.encode('utf-8'))
        return enb64_str.decode("utf-8")

    # base64对url解密
    @staticmethod
    def url_b64_decrypt(data: str) -> str:
        deb64_str = base64.urlsafe_b64decode(data)
        return deb64_str.decode("utf-8")

    # hashlib md5加密
    @staticmethod
    def hash_md5_encrypt(data: (str, bytes)) -> str:
        if isinstance(data, str):
            data = data.encode('utf-8')
        md5 = hashlib.md5()
        md5.update(Constant.ENCRYPT_KEY.encode('utf-8'))
        md5.update(data)
        return md5.hexdigest()

    # hashlib sha1加密
    @staticmethod
    def hash_sha1_encrypt(data: (str, bytes)) -> str:
        if isinstance(data, str):
            data = data.encode('utf-8')
        md5 = hashlib.sha1()
        md5.update(Constant.ENCRYPT_KEY.encode('utf-8'))
        md5.update(data)
        return md5.hexdigest()

    # hashlib sha256加密
    @staticmethod
    def hash_sha256_encrypt(data: (str, bytes)) -> str:
        if isinstance(data, str):
            data = data.encode('utf-8')
        md5 = hashlib.sha256()
        md5.update(Constant.ENCRYPT_KEY.encode('utf-8'))
        md5.update(data)
        return md5.hexdigest()

    # # Crypto AES加密
    # @staticmethod
    # def crypto_encrypt(data: (str, bytes)) -> str:
    #     """
    #     data大于16位，返回64位字符；小于16位，返回32位字符
    #     :param data:
    #     :return:
    #     """
    #     if isinstance(data, str):
    #         data = data.encode('utf-8')
    #     cipher = AES.new(Constant.ENCRYPT_KEY.encode('utf8'), AES.MODE_ECB)
    #     msg = cipher.encrypt(pad(data, Constant.BLOCK_SIZE))
    #     return msg.hex()
    #
    # # Crypto AES解密
    # @staticmethod
    # def crypto_decrypt(data: str) -> str:
    #     decipher = AES.new(Constant.ENCRYPT_KEY.encode('utf8'), AES.MODE_ECB)
    #     msg_dec = decipher.decrypt(bytes.fromhex(data))
    #     return unpad(msg_dec, Constant.BLOCK_SIZE).decode()
    #
    #
